package reading.util.utils;

import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * java 8 time utils
 *
 * @author yangbajing(yangbajing @ gmail.com) on 2016-09-9.
 */
public class TimeUtils {
    public static final ZoneOffset ZONE_OFFSET = ZoneOffset.of("+08");

    private static final DateTimeFormatter YYYYMMDDHHMMSS = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private static final DateTimeFormatter YYYYMMDD = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private static final DateTimeFormatter HHMMSS = DateTimeFormatter.ofPattern("HH:mm:ss");

    private static final SimpleDateFormat HH_MM_SS = new SimpleDateFormat("yyyy/MM/dd");

    public static long nowSeconds() {
        return nowMillis() / 1000;
    }

    public static long nowMillis() {
        return System.currentTimeMillis();
    }

    public static LocalDate toLocalDate(Date date) {
        return toLocalDateTime(date).toLocalDate();
    }

    public static LocalDateTime toLocalDateTime(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    public static String dateFormat(Date date) {
        synchronized (HH_MM_SS) {
            return HH_MM_SS.format(date);
        }
    }

    public static LocalDate parseLocalDate(String date) {
        return LocalDate.parse(date);
    }

    public static String formatLocalDateTime(LocalDateTime localDateTime) {
        return localDateTime.format(YYYYMMDDHHMMSS);
    }

    public static String formatLocalDate(LocalDate localDate) {
        return localDate.format(YYYYMMDD);
    }

    public static String formatLocalTime(LocalTime localTime) {
        return localTime.format(HHMMSS);
    }

    public static Date toDate(LocalDate ldt) {
        return new Date(ldt.atStartOfDay().toInstant(ZONE_OFFSET).toEpochMilli());
    }

    public static Date toDate(LocalDateTime ldt) {
        return new Date(ldt.toInstant(ZONE_OFFSET).toEpochMilli());
    }

    public static String formatDate(Date date) {
        return formatDate(new java.sql.Date(date.getTime()));
    }

    public static String formatDate(java.sql.Date date) {
        return formatLocalDate(date.toLocalDate());
    }

    public static String formatTime(java.sql.Time time) {
        return formatLocalTime(time.toLocalTime());
    }

    public static String formatTimestamp(java.sql.Timestamp timestamp) {
        return formatLocalDateTime(timestamp.toLocalDateTime());
    }

    public static boolean validateTime(String time, String pattern) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime.parse(time, dtf);
        return true;
    }
}